<!--
 * @Author: YMJ
 * @Date: 2020-10-30 10:47:06
-->
<template>
  <div>
    <!-- 列表 -->
    <tab-list
      ref="list"
      :searchs="searchs"
      :list-hedar="listHedar"
      :params="params"
      :api-function="apiFunction"
      other-show
      @init-params="initParams"
      @add-list="openEditBox()"
    >
      <el-image
        slot="backImg"
        slot-scope="scope"
        style="width: 50px; height: 50px"
        :src="scope.value.backImg"
        :preview-src-list="[scope.value.backImg]"
      />
      <span
        slot="isHot"
        slot-scope="scope"
        :style="`color:${scope.value.isHot ? '#67C23A' : '#909399'}`"
      >
        {{ scope.value.isHot ? '热门城市' : '普通城市' }}
      </span>
      <template slot="operate" slot-scope="scope">
        <el-button type="text" size="small" @click="openEditBox(scope.value.id)">编辑</el-button>
        <el-button type="text" size="small" @click="changeHot(!scope.value.isHot, scope.value.id)">{{ scope.value.isHot ? '取消' : '设为' }}热门</el-button>
      </template>
    </tab-list>
    <el-dialog
      :title="`${detail ? '编辑' : '添加'}城市`"
      :visible.sync="toastShow"
      width="40%"
      :close-on-click-modal="false"
      @open="$refs.form && $refs.form.resetForm()"
    >
      <edit-form
        ref="form"
        :rules="rules"
        :edit-list="editList"
        :form="form"
        @uploade="(url, config) => {form.backImg = url;fileConfig = config}"
        @on-submit="addOrEdit()"
      >
        <div slot="linkage">
          <el-select
            v-model="areaCode1"
            clearable
            class="mr"
            placeholder="请选择"
            @change="areaCode2='';areaCode3='';changeArea()"
          >
            <el-option
              v-for="item in areaTree1"
              :key="item.areaCode"
              :label="item.areaName"
              :value="item.areaCode"
            />
          </el-select>
          <el-select
            v-model="areaCode2"
            clearable
            class="mr"
            :disabled="areaCode1 === ''"
            placeholder="请选择"
            @change="areaCode3='';changeArea()"
          >
            <el-option
              v-for="item in areaTree2"
              :key="item.areaCode"
              :label="item.areaName"
              :value="item.areaCode"
            />
          </el-select>
          <!-- <el-select
            v-model="areaCode3"
            clearable
            :disabled="areaCode2 === ''"
            placeholder="请选择"
          >
            <el-option
              v-for="item in areaTree3"
              :key="item.areaCode"
              :label="item.areaName"
              :value="item.areaCode"
            />
          </el-select> -->
        </div>
      </edit-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="$refs.form.ruleFrom()">确 定</el-button>
        <el-button @click="toastShow = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
cityList
// 组件
import tabList from '@/components/admin/tab-list.vue'
import editForm from '@/components/admin/edit-form.vue'
// 公共方法
import { asyncApiFun, openMessageBox, initEditList } from '@/utils/utils'
// 接口
import { cityList, cityHot, cityDetail, cityEdit } from '@/api/operate.js'
import { areaTree } from '@/api/basics.js'
// 页面配置
import { listHedar, searchs, editList, rules } from './config/city.config.js'
export default {
  components: {
    tabList,
    editForm
  },
  data() {
    return {
      fileConfig: {},
      areaTree1: [],
      areaCode1: '',
      areaTree2: [],
      areaCode2: '',
      areaTree3: [],
      areaCode3: '',
      toastShow: false,
      editList,
      rules,
      form: {},
      searchs,
      params: {},
      listHedar,
      apiFunction: cityList,
      detail: null
    }
  },
  watch: {
    areaCode1(val) {
      if (val === '') return
      this.form.areaCode = this.areaCode1;
      this.getAreaTree('1')
    },
    areaCode2(val) {
      if (val === '') return
       this.form.areaCode = this.areaCode2;
      this.getAreaTree('2')
    },
    areaCode3(val) {
      if (val === '') return
      this.getAreaTree('3')
    }
  },
  created() {
    this.getAreaTree()
  },
  methods: {
    changeArea() {
      this.$nextTick(() =>{
        let _area;
        if (this.areaCode2) {
          _area = this.areaTree2.find(item => item.areaCode === this.areaCode2)
        } else if (this.areaCode1) {
          _area = this.areaTree1.find(item => item.areaCode === this.areaCode1)
        }
        this.form.areaName = _area.areaName;
        console.log(this.form);
      })
    },
    // 获取行政区域3级联动
    async getAreaTree(type = '0') {
      if (type !== '3') {
        const params = {}
        params.sup = (type === '0' ? '000000' : this['areaCode' + type])
        const [res] = await asyncApiFun(areaTree, params)
        if (res) {
          this[`areaTree${Number(type) + 1}`] = res.data
        }
      }
      this.getAreaCode()
    },
    // 将行政区域代码加进form中
    getAreaCode() {
      const _arr = ['areaCode1', 'areaCode2', 'areaCode3']
      let _code = this.areaCode3
      for (let i = 0; i < _arr.length; i++) {
        if (!this[_arr[i]]) {
          _code = this[_arr[i - 1]]
          break
        }
      }
      this.form.areaCode = _code
    },
    // 设为/取消热门
    changeHot(isHot, id) {
      const _content = isHot ? '设置后，该城市默认热门城市排序为1，是否确认？' : '设置后，该城市降为普通城市，是否确认？'
      const _title = isHot ? '设为热门' : '取消热门'
      openMessageBox({
        content: _content,
        title: _title
      }, async boole => {
        if (boole) {
          const [res] = await asyncApiFun(cityHot, { id, isHot })
          if (res) this.$refs.list.getList()
        }
      })
    },
    // 打开新增或者编辑弹窗
    openEditBox(id) {
      this.getDetail(id)
      this.toastShow = true
    },
    // 获取城市详情
    async getDetail(id) {
      let _detail = null
      if (id) {
        const [res] = await asyncApiFun(cityDetail, id)
        if (res) {
          _detail = res.data
          this.areaCode1 = _detail.province || ''
          this.areaCode2 = _detail.city || ''
          this.areaCode3 = _detail.area || ''
        }
      } else {
        this.areaCode1 = this.areaCode2 = this.areaCode3 = ''
      }
      this.detail = _detail
      // 重置编辑框数据
      const _obj = initEditList(this.editList, this.detail)
      if (this.form.areaCode) _obj.areaCode = this.form.areaCode
      this.form = _obj
    },
    async addOrEdit() {
      const parasm = {
        ...this.form,
        province: this.areaCode1,
        city: this.areaCode2,
        // area: this.areaCode3,
        areaCode: ''
      }
      const _arr = ['areaCode1', 'areaCode2', 'areaCode3']
      _arr.forEach(item => {
        if (this[item]) parasm.areaCode = this[item]
      })
      if (!parasm.areaCode) {
        this.form.areaCode = ''
        return
      }
      if (this.detail) parasm.id = this.detail.id
      const [res] = await asyncApiFun(cityEdit, parasm, this.fileConfig)
      if (res) {
        this.$refs.list.getList()
        this.toastShow = false
      }
    },
    initParams(param) {
      if (param.type) {
        param.type = Boolean(Number(param.type))
      }
      this.params = param
    }
  }
}
</script>

<style lang="scss" scoped>
  .el-select{
    width: 32%;
    &.mr{
      margin-right: 2%;
    }
  }
</style>
